<?php

/**
 * This is the model class for table "esportista".
 *
 * The followings are the available columns in table 'esportista':
 * @property integer $idEsportista
 * @property string $dataAlta
 * @property integer $DNI
 * @property string $cognoms
 * @property string $nom
 * @property string $dataNaixement
 * @property string $sexe
 * @property string $codiCatSalut
 * @property integer $idClub
 *
 * The followings are the available model relations:
 * @property Club $idClub0
 * @property Llicencia[] $llicencias
 * @property Participacio[] $participacios
 * @property Titol[] $titols
 */
class Esportista extends CActiveRecord
{
    /**
	 * Returns the static model of the specified AR class.
	 * @return Esportista the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'esportista';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('dataAlta, DNI, cognoms, nom, dataNaixement, sexe, codiCatSalut, idClub', 'required'),
			array('idClub', 'numerical', 'integerOnly'=>true),
			array('cognoms, nom', 'length', 'max'=>45),
            array('sexe', 'in', 'range'=>array('M','F'), 'message'=>'Si us plau, indica si l\'esportista és Home o Dona'),
			array('sexe', 'length', 'max'=>1),
			array('codiCatSalut', 'length', 'max'=>20),
            array('dataNaixement', 'type', 'type'=>'date', 'message'=>'<b>{attribute}</b>: Si us plau, introdueix la data amb el format "dd/mm/aaaa".', 'dateFormat'=>Yii::app()->locale->dateFormat),
            array('dataAlta', 'type', 'type'=>'date', 'message'=>'<b>{attribute}</b>: Si us plau, introdueix la data amb el format "dd/mm/aaaa".', 'dateFormat'=>Yii::app()->locale->dateFormat),
            array('dataNaixement', 'edatMinima'),
            array('codiCatSalut', 'unique', 'message'=>'Ja existeix un esportista amb el codi CatSalut <b>{value}</b>.'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('idEsportista, dataAlta, DNI, cognoms, nom, dataNaixement, sexe, codiCatSalut, idClub', 'safe', 'on'=>'search'),
		);
	}
    
    /**
     * @return comprova que l'esportista tingui l'edat mínima
     */
    public function edatMinima( $attribute, $params) {
        if ($this->edat<Yii::app()->params['edatMinima'])
            $this->addError('dataNaixement','L\'esportista no té l\'edat mínima.');
    }

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'clubPertany' => array(self::BELONGS_TO, 'Club', 'idClub'),
			'llicencies' => array(self::HAS_MANY, 'Llicencia', 'idEsportista'),
			'participacions' => array(self::HAS_MANY, 'Participacio', 'idEsportista'),
			'titols' => array(self::HAS_MANY, 'Titol', 'idEsportista'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'idEsportista' => 'Codi',
			'dataAlta' => 'Data d\'alta',
			'DNI' => 'DNI',
			'cognoms' => 'Cognoms',
			'nom' => 'Nom',
			'dataNaixement' => 'Data de naixement',
			'sexe' => 'Sexe',
			'codiCatSalut' => 'Codi CatSalut',
			'idClub' => 'Club',
            'nomClub' => 'Nom del club',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('idEsportista',$this->idEsportista);
		$criteria->compare('dataAlta',$this->dataAlta,true);
		$criteria->compare('DNI',$this->DNI);
		$criteria->compare('cognoms',$this->cognoms,true);
		$criteria->compare('nom',$this->nom,true);
		$criteria->compare('dataNaixement',$this->dataNaixement,true);
		$criteria->compare('sexe',$this->sexe,true);
		$criteria->compare('codiCatSalut',$this->codiCatSalut,true);
		$criteria->compare('idClub',$this->idClub);        
        
		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>array(
                    'cognoms'=>false, //false= ordre ascendent, true= ordre descendent
                    'nom'=>false,
                )),
            'pagination'=>array(
                'pageSize'=>Yii::app()->params['itemsPagina']),

		));
	}
    
    protected function beforeSave()
    {   
        foreach($this->metadata->tableSchema->columns as $columnName => $column){
                if ($column->dbType == 'date'){
                        $this->$columnName = date('Y-m-d', CDateTimeParser::parse($this->$columnName, Yii::app()->locale->dateFormat));
                }elseif ($column->dbType == 'datetime'){
                        $this->$columnName = date('Y-m-d H:i:s', CDateTimeParser::parse($this->$columnName, Yii::app()->locale->dateFormat));
                }
        
        }
        
        return true;
    }
    
    protected function afterFind()
    {
        foreach($this->metadata->tableSchema->columns as $columnName => $column){
                        
            if (!strlen($this->$columnName)) continue;
                        
            if ($column->dbType == 'date'){                         
                $this->$columnName = Yii::app()->dateFormatter->formatDateTime(
                    CDateTimeParser::parse($this->$columnName, 'yyyy-MM-dd'),'medium',null);
            }elseif ($column->dbType == 'datetime'){
                $this->$columnName = Yii::app()->dateFormatter->formatDateTime(
                    CDateTimeParser::parse($this->$columnName, 'yyyy-MM-dd hh:mm:ss'));
            }
        }
        return true;
    }
    
    public function getSexeStr() {
        if ($this->sexe== 'M') return "Masculí";
        else return "Femení";
    }
    
    public function getNomClub() {
        return $this->clubPertany->nom;
    }
    
    public function getCognomsNom() {
        return $this->cognoms.', '.$this->nom;
    }
    
    public function getNomDataCodi() {
        return $this->cognomsNom.' - '.$this->dataNaixement.' ('.(string)$this->idEsportista.')';
    }
    
    public function getEdat() {
        if ($this->dataNaixement!=null) {
            list($dia, $mes, $any)= explode("/", $this->dataNaixement);
            $diff_anys= date("Y") - $any;
            $diff_mes= date("m") - $mes;
            $diff_dia= date("d") - $dia;
            if ($diff_dia<0 || $diff_mes<0) $diff_anys--;
        
            return $diff_anys;
        }
        return NULL;
    }
}